import { reqUserLogin, reqUserLogout } from '@/apis';

const state = {
  userInfo: {
    nickName: localStorage.getItem('nickName'),
    token: localStorage.getItem('token')
  }
}

const actions = {
  // 用户登录
  async userLogin(context, payload){
    // 发送登录请求
    const res = await reqUserLogin(payload)

    if(res.code == 200) { // 登录成功
      // 存入本地
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('nickName', res.data.nickName)

      context.commit('SAVE_USER_INFO', res.data)

    } else {
      return Promise.reject(res.message)
      alert(res.message)
    }
  },
  // 退出登录
  async userLogout(context, payload){
    const res = await reqUserLogout()
    if(res.code == 200) {
      // 清除 vuex 中的登录信息
      context.commit('REMOVE_USER_INFO')
      // 清除本地存储的 token
      localStorage.removeItem('token')
      localStorage.removeItem('nickName')
    } else {
      return Promise.reject(res.message)
    }
  }
}

const mutations = {
  SAVE_USER_INFO(state, payload){
    state.userInfo = payload
  },
  REMOVE_USER_INFO(state, payload){
    state.userInfo = {}
  }
}

const getters = {

}

export default {
  namespaced: true, 
  state, 
  actions,
  mutations,
  getters
}